from flask import Flask,request,after_this_request
from flask_cors import CORS
import json,datetime,os
from threading import Thread

# 创建应用实例
app=Flask(__name__)
# 配置允许跨域
CORS(app,supports_credentials=True)
# 加载库存信息
with open('static/bank.json','r') as f:
    bank_info=json.load(f)
# 初始化订单计数
order_count=0
# 获取营业日期
business_day=datetime.date.today().strftime('%Y%m%d')

# 静态资源
@app.get('/assets/<string:filename>')
def source(filename):
    # 根据资源类型修改响应头
    @after_this_request
    def check_content_type(response):
        if filename.endswith('.js'):
            response.headers['Content-Type']='application/javascript'
        if filename.endswith('.css'):
            response.headers['Content-Type']='text/css'
        if filename.endswith('.png'):
            response.headers['Content-Type']='image/png'
        return response
    # 读取资源作为响应内容返回
    f=open(f'client/assets/{filename}','rb')
    feedback=f.read()
    f.close()
    return feedback

# 打开点餐
@app.get('/<int:id>')
def menu(id):
    # 读取页面作为响应内容返回
    f=open('client/index.html','r')
    feedback=f.read()
    f.close()
    return feedback

# 提示页面
@app.get('/tips.html')
def tips():
    # 读取页面作为响应内容返回
    f=open('client/tips.html','r')
    feedback=f.read()
    f.close()
    return feedback

# 提交订单
@app.post('/')
def result():
    # 生成下单菜品列表
    order_detail=request.get_json(force=True)
    dish_list=list(map(lambda x:x.split('-')[0],order_detail['list'].keys()))
    # 校验库存状态
    order_success=all(map(lambda x:bank_info.get(x,True),dish_list))
    global order_count
    if order_success:
        # 增加订单计数
        order_count+=1
        # 生成订单编号
        order_id=int(business_day+str(order_count).rjust(4,'0'))
        order_data={}
        # 创建子线程以运行子进程发送订单到通知页面
        data=f'\'{json.dumps(order_detail)}\''
        t=Thread(target=lambda:os.system(f'python link.py {data}'))
        t.start()
    else:
        order_id='<获取失败>'
        # 生成订单更新数据
        order_data={ x:bank_info[x] for x in dish_list if not bank_info[x]}
    # 返回下单结果
    return dict(success=order_success,data=order_data,id=order_id)

# 获取库存
@app.get('/db')
def query_data():
    return bank_info

# 通知页面
@app.get('/notice')
def order_notice():
    # 读取页面作为响应内容返回
    f=open('test.html','r')
    feedback=f.read()
    f.close()
    return feedback

# 修改库存
@app.post('/db')
def modify_data():
    # 业务逻辑尚未完善
    return

if __name__ == '__main__':
    # 配置监听端口
    with open('static/config.json','r') as f:
        port=json.load(f)['port']['http']
    # 打印提示信息
    print('HTTP Server running...')
    # 运行服务器
    app.run(host='0.0.0.0',port=port,debug=True)
